﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Urs.Admin.Models.Stores;
using Urs.Data.Domain.Stores;
using Urs.Services.Stores;
using Urs.Services.Localization;
using Urs.Services.Logging;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Extensions;
using Urs.Framework.Kendoui;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class GoodsSpecController : BaseAdminController
    {
        #region Fields

        private readonly IGoodsSpecService _goodsSpecService;
        private readonly ILocalizationService _localizationService;
        private readonly IActivityLogService _activityLogService;
        private readonly IPermissionService _permissionService;

        #endregion Fields

        #region Constructors

        public GoodsSpecController(IGoodsSpecService goodsSpecService,

            ILocalizationService localizationService, IActivityLogService activityLogService,
            IPermissionService permissionService)
        {
            this._goodsSpecService = goodsSpecService;


            this._localizationService = localizationService;
            this._activityLogService = activityLogService;
            this._permissionService = permissionService;
        }

        #endregion

        #region Methods

        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            return View();
        }

        public IActionResult ListJson(PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var goodsSpecs = _goodsSpecService.GetAllGoodsSpecs();
            var result = new ResponseResult
            {
                data = goodsSpecs.Select(x => x.ToModel<GoodsSpecModel>()),
                count = goodsSpecs.Count()
            };
            return Json(result);
        }

        public IActionResult Search(string name)
        {
            var goodsSpecs = _goodsSpecService.GetAllGoodsSpecs(name);

            var list = new List<GoodsSpecModel>();

            foreach (var item in goodsSpecs)
            {
                if (!item.Deleted)
                    list.Add(new GoodsSpecModel() { Id = item.Id, Name = item.Name });
            }

            return Json(new { data = list });
        }

        //edit
        public IActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var model = new GoodsSpecModel();
            var goodsSpec = _goodsSpecService.GetGoodsSpecById(id);
            if (goodsSpec == null)
                return View(model);
            else
                model = goodsSpec.ToModel<GoodsSpecModel>();
            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(GoodsSpecModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var goodsSpec = _goodsSpecService.GetGoodsSpecById(model.Id);
            if (goodsSpec == null)
            {
                goodsSpec = new GoodsSpec();
                goodsSpec.Name = model.Name;
                _goodsSpecService.InsertGoodsSpec(goodsSpec);
                _activityLogService.InsertActivity("AddNewGoodsSpec", _localizationService.GetResource("ActivityLog.AddNewGoodsSpec"), goodsSpec.Name);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    goodsSpec.Name = model.Name;
                    _goodsSpecService.UpdateGoodsSpec(goodsSpec);

                    //activity log
                    _activityLogService.InsertActivity("EditGoodsSpec", _localizationService.GetResource("ActivityLog.EditGoodsSpec"), goodsSpec.Name);
                }
            }
            return Json(new { success = 1, data = new { Id = goodsSpec.Id, Name = goodsSpec.Name } });
        }
        //delete
        [HttpPost]
        public IActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var goodsSpec = _goodsSpecService.GetGoodsSpecById(id);
            if (goodsSpec == null)
                return Json(new { error = 1 });

            goodsSpec.Deleted = true;
            _goodsSpecService.UpdateGoodsSpec(goodsSpec);

            //activity log
            _activityLogService.InsertActivity("DeleteGoodsSpec", _localizationService.GetResource("ActivityLog.DeleteGoodsSpec"), goodsSpec.Name);

            return Json(new { succcess = 1 });
        }


        public IActionResult ValueList(int Id)
        {
            ViewBag.GoodsSpecId = Id;
            return View();
        }

        [HttpPost]
        public IActionResult ValueListJson(int goodsSpecId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var values = _goodsSpecService.GetGoodsSpecValues(goodsSpecId);
            var result = new ResponseResult
            {
                data = values.Select(x =>
                {
                    return new GoodsSpecValueModel()
                    {
                        Id = x.Id,
                        Name = x.Name,
                    };
                }),
                count = values.Count()
            };
            return Json(result);
        }


        public IActionResult ValueEdit(int id, int goodsAttrId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var model = new GoodsSpecValueModel();
            var goodsAttr = _goodsSpecService.GetGoodsSpecById(goodsAttrId);
            if (goodsAttr != null)
                model.GoodsSpecId = goodsAttrId;
            var value = _goodsSpecService.GetGoodsSpecValueById(id);
            if (value != null)
            {
                model.Id = value.Id;
                model.Name = value.Name;
            }
            return View(model);
        }

        [HttpPost]
        public IActionResult ValueEdit(GoodsSpecValueModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var value = _goodsSpecService.GetGoodsSpecValueById(model.Id);
            if (value == null)
            {
                value = new GoodsSpecValue();
                value.GoodsSpecId = model.GoodsSpecId;
                value.Name = model.Name;
                _goodsSpecService.InsertGoodsSpecValue(value);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    value.Name = model.Name;
                    _goodsSpecService.UpdateGoodsSpecValue(value);
                }
            }
            return Json(new { success = 1, data = new { Id = value.Id, GoodsSpecId = value.GoodsSpecId, Name = value.Name } });
        }
        /// <summary>
        /// 删除规格值
        /// </summary>
        /// <param name="id">规格值Id</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ValueDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageGoods))
                return HttpUnauthorized();

            var pvav = _goodsSpecService.GetGoodsSpecValueById(id);
            if (pvav == null)
                return Json(new { error = 1 });

            pvav.Deleted = true;
            _goodsSpecService.UpdateGoodsSpecValue(pvav);

            return Json(new { success = 1 });
        }

        /// <summary>
        /// 商品规格值
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public IActionResult GoodsValue(int goodsId)
        {
            var goodsSpecMappings = _goodsSpecService.GetGoodsSpecMappingByGoodsId(goodsId);

            var list = new List<GoodsValueModel>();


            foreach (var item in goodsSpecMappings)
            {
                var attr = _goodsSpecService.GetGoodsSpecById(item.GoodsSpecId);

                if (attr != null && list.FirstOrDefault(q => q.Id == attr.Id) == null)
                {
                    list.Add(new GoodsValueModel() { Id = attr.Id, Name = attr.Name });
                }

                var attrModel = list.FirstOrDefault(q => q.Id == attr.Id);

                var attrValue = _goodsSpecService.GetGoodsSpecValueById(item.GoodsSpecValueId);
                if (attrValue != null)
                {
                    attrModel.Values.Add(new GoodsValueModel.AttrValue() { Id = item.GoodsSpecValueId, Name = attrValue.Name });
                }
            }

            return Json(new { data = list });
        }

        #endregion
    }
}
